import React, { Component } from 'react';
import moment from 'moment';
import { Form, Input, message, Modal, Select, Button, Card, Tooltip } from 'antd';
import IconButton from '@/components/IconButton';
import { maxLength } from '@/utils/form';
import { REGION_ADDRESS_TYPE, REGION_TYPE } from '@/Constants';
import { FULL_NAME_RULE, EMAIL_RULE, CODE_RULE, MOBILE_RULE } from '@/Constants/rules';
import api from '@/api';
import OrgTree from '../OrgTree/OrgTree';

const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea, Search } = Input;

@Form.create()
class UpdateUserForm extends Component {
  state = {
    checkedOrgs: [],
    checkedNodes: [],
    checkedOrgKeys: [],
    selectedOrgKeys: [],
    orgVisible: false,
  };
  async componentDidMount() {
    const { orgTree, currentUser } = this.props;
    this.setState({
      selectedOrgKeys: orgTree[0] ? [orgTree[0].id] : [],
    });
  }

  componentWillReceiveProps(nextProps) {
    const { currentUser } = nextProps;
    if (this.props.currentUser !== currentUser) {
      let checkedOrgs = [];
      let checkedNodes = [];
      currentUser.orgs &&
        currentUser.orgs.forEach(org => {
          checkedOrgs.push({
            id: org.id,
            key: org.id,
            code: org.id,
            name: org.shortName,
          });
        });
      this.setState({
        checkedOrgs,
        checkedNodes: checkedOrgs,
      });
    }
  }

  handleInput = e => {
    let val = e.target.value;
    val = val.trim();
    val = val.substr(0, 30);
    e.target.value = val;
  };
  checkCode = (rule, value = '', callback) => {
    const { currentUser } = this.props;
    if (value == '') {
      return callback();
    }
    let payload = {
      [rule.field]: value,
      id: currentUser.id,
    };
    api.user.userManage
      .checkCode({
        queryParams: payload,
      })
      .then(res => {
        if (!res.data) {
          callback(rule.message);
        } else {
          callback();
        }
      });
  };
  handleTreeCheck = (checkedKeys, e) => {
    let checkedNodes = e.checkedNodes.map(node => {
      return {
        id: node.props.dataRef.id,
        key: node.props.dataRef.id,
        code: node.props.dataRef.id,
        name: node.props.dataRef.shortName,
      };
    });
    this.setState({
      checkedOrgKeys: checkedKeys,
      checkedNodes,
    });
  };

  handleTreeNodeSelect = selectedKeys => {
    this.setState({
      selectedOrgKeys: selectedKeys,
    });
  };

  handleOrgCheckedCancle = () => {
    this.setState({
      orgVisible: false,
    });
  };

  handleOrgCheckedSubmit = () => {
    const { checkedNodes } = this.state;
    this.props.form.setFieldsValue({ orgs: checkedNodes });
    this.setState({
      checkedOrgs: checkedNodes,
    });
    this.handleOrgCheckedCancle();
  };

  handleSelectOnChange = value => {
    console.log(value);
  };

  handleAddOrgs = () => {
    this.setState({
      orgVisible: true,
      checkedOrgKeys: (this.state.checkedNodes || []).map(org => org.id),
    });
  };

  render() {
    const {
      updateModalVisible,
      form,
      handleUpdate,
      handleUpdateModalVisible,
      currentUser,
      orgTree,
      loading = false
    } = this.props;
    const { orgVisible, selectedOrgKeys, checkedOrgKeys, checkedOrgs } = this.state;
    const okHandle = () => {
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        const fullName = fieldsValue.fullName.trim();
        handleUpdate({
          ...fieldsValue,
          orgs: fieldsValue.orgs.map(org => {
            return { id: org.id };
          }),
          fullName,
        });
        form.resetFields();
      });
    };

    return (
      <>
        <Modal
          maskClosable={false}
          keyboard={false}
          destroyOnClose
          title="编辑用户"
          visible={updateModalVisible}
          confirmLoading={loading}
          onOk={okHandle}
          onCancel={() => handleUpdateModalVisible()}
        >
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="账号">
            {form.getFieldDecorator('userName', {
              rules: [
                { required: true, message: '请输入账号', whitespace: true },
                { pattern: CODE_RULE.PATTERN, message: CODE_RULE.MESSAGE },
                { validator: this.checkCode, message: '账号已存在' },
              ],
              validateTrigger: 'onBlur',
              initialValue: currentUser.userName,
            })(<Input disabled={true} maxLength={15} />)}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="姓名">
            {form.getFieldDecorator('fullName', {
              rules: [
                { required: true, message: '请输入姓名', whitespace: true },
                { pattern: FULL_NAME_RULE.PATTERN, message: FULL_NAME_RULE.MESSAGE },
              ],
              initialValue: currentUser.fullName,
            })(<Input maxLength={30} onBlur={e => this.handleInput(e)} />)}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="组织">
            {form.getFieldDecorator('orgs', {
              rules: [{ required: true, message: '请选择组织' }],
              initialValue: checkedOrgs,
            })(
              <Select
                mode="tags"
                labelInValue
                optionLabelProp="text"
                style={{ width: '100%' }}
                open={false}
                disabled
              >
                {checkedOrgs.map(item => (
                  <Option key={item.key} value={item.key} text={item.name} />
                ))}
              </Select>
            )}
            <IconButton
              title="编辑"
              icon="icon-edit"
              style={{ position: 'absolute', top: -7, right: -60 }}
              onClick={this.handleAddOrgs}
            />
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="手机">
            {form.getFieldDecorator('mobilePhone', {
              rules: [
                { required: true, message: '请输入手机号码', whitespace: true },
                { pattern: MOBILE_RULE.PATTERN, message: MOBILE_RULE.MESSAGE },
                { validator: this.checkCode, message: '手机已存在' },
              ],
              validateTrigger: 'onBlur',
              initialValue: currentUser.mobilePhone,
            })(<Input maxLength={11} />)}
          </FormItem>

          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="邮箱">
            {form.getFieldDecorator('email', {
              rules: [
                { required: true, message: '请输入邮箱地址', whitespace: true },
                { type: 'email', message: '请输入正确的邮箱地址' },
                { validator: this.checkCode, message: '邮箱已存在' },
              ],
              validateTrigger: 'onBlur',
              initialValue: currentUser.email,
            })(<Input maxLength={100} />)}
          </FormItem>
        </Modal>
        <Modal
          maskClosable={false}
          keyboard={false}
          destroyOnClose
          title="吉祥航空物流"
          visible={orgVisible}
          onOk={this.handleOrgCheckedSubmit}
          onCancel={this.handleOrgCheckedCancle}
        >
          <Card style={{ height: '480px', overflowY: 'auto' }} bordered={false}>
            <OrgTree
              expandedAllNodes={true}
              checkStrictly={true}
              checkable={true}
              checkedKeys={checkedOrgKeys}
              onCheck={this.handleTreeCheck}
              selectedKeys={selectedOrgKeys}
              onTreeNodeSelect={this.handleTreeNodeSelect}
              orgTree={orgTree}
            />
          </Card>
        </Modal>
      </>
    );
  }
}

export default UpdateUserForm;
